package com.example.blog.util;

import com.qcloud.cos.COSClient;
import com.qcloud.cos.ClientConfig;
import com.qcloud.cos.auth.BasicCOSCredentials;
import com.qcloud.cos.auth.COSCredentials;
import com.qcloud.cos.exception.CosClientException;
import com.qcloud.cos.exception.CosServiceException;
import com.qcloud.cos.model.*;
import com.qcloud.cos.region.Region;
import com.tencent.cloud.CosStsClient;
import org.json.JSONException;
import org.json.JSONObject;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.validation.annotation.Validated;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletResponse;
import java.io.*;
import java.util.ResourceBundle;
import java.util.TreeMap;

public class TencentUploadUtilOld {

    //腾讯云的SecretId
    @Value("tencent.SecretId")
    private static String secretId;

    //腾讯云的SecretKey
    @Value("tencent.SecretKey")
    private static String secretKey;

    //腾讯云的bucket (存储桶)
    @Value("tencent.bucket")
    private static String bucket;

    //腾讯云的region(bucket所在地区)
    @Value("tencent.region")
    private static String region;

    //腾讯云的allowPrefix(允许上传的路径)
    @Value("tencent.allowPrefix")
    private static String allowPrefix;

    //腾讯云的临时密钥时长(单位秒)
    @Value("tencent.durationSeconds")
    private static String durationSeconds;

    //腾讯云的访问基础链接
    @Value("tencent.baseUrl")
    private static String baseUrl;
    //读取配置文件，初始化配置
//    static {
//        ResourceBundle bundle = ResourceBundle.getBundle("application");
//        secretId = bundle.getString("tencent.SecretId");
//        secretKey = bundle.getString("tencent.SecretKey");
//        bucket = bundle.getString("tencent.bucket");
//        region = bundle.getString("tencent.region");
//        allowPrefix = bundle.getString("tencent.allowPrefix");
//        durationSeconds = bundle.getString("tencent.durationSeconds");
//        baseUrl = bundle.getString("tencent.baseUrl");
//    }



    /**
     * 上传文件
     *
     * @param path 文件服务器下的根路径,即key,如: doc/picture.jpg
     * @param file
     * @return 成功返回文件路径,失败返回null
     */
    public static String uploadFile(String path, File file) throws JSONException {
        //获取临时密钥
        JSONObject temp = getTempKey();
        // 用户基本信息:解析临时密钥中的相关信息
        String tmpSecretId = temp.getJSONObject("credentials").getString("tmpSecretId");
        String tmpSecretKey = temp.getJSONObject("credentials").getString("tmpSecretKey");
        String sessionToken = temp.getJSONObject("credentials").getString("sessionToken");

        // 1 初始化用户身份信息(secretId, secretKey)
        COSCredentials cred = new BasicCOSCredentials(tmpSecretId, tmpSecretKey);
        // 2 设置 bucket 区域
        ClientConfig clientConfig = new ClientConfig(new Region(region));
        // 3 生成 cos 客户端
        COSClient cosclient = new COSClient(cred, clientConfig);
        // bucket名需包含appid
        String bucketName = bucket;
        // 上传 object, 建议 20M 以下的文件使用该接口
        PutObjectRequest putObjectRequest = new PutObjectRequest(bucketName, path, file);
        // 设置 x-cos-security-token header 字段
        ObjectMetadata objectMetadata = new ObjectMetadata();
        objectMetadata.setSecurityToken(sessionToken);
        putObjectRequest.setMetadata(objectMetadata);
        String rtValue = null;
        try {
            PutObjectResult putObjectResult = cosclient.putObject(putObjectRequest);
            // 成功：putobjectResult 会返回文件的 etag
            //String etag = putObjectResult.getETag();
            rtValue = baseUrl + path;
        } catch (CosServiceException e) {
            //失败，抛出 CosServiceException
            e.printStackTrace();
        } catch (CosClientException e) {
            //失败，抛出 CosClientException
            e.printStackTrace();
        } finally {
            // 关闭客户端
            cosclient.shutdown();
            //返回文件的网络访问url
            return rtValue;
        }
    }

    public static void downloadold(HttpServletResponse response, String path) throws IOException {
        // 初始化用户身份信息(secretId, secretKey)
        COSCredentials cred = new BasicCOSCredentials("AKIDb0A1h6v5fy2oKicMaXMxHMJM8fwvs9OO","y6zbHgneZDbiX1EAqFO6YiiTx94j7D3j");
        // 设置bucket的区域, COS地域的简称请参照 https://www.qcloud.com/document/product/436/6224
        ClientConfig clientConfig = new ClientConfig(new Region("ap-nanjing"));
        // 生成cos客户端
        COSClient cosclient = new COSClient(cred, clientConfig);
        String key = path;
        String bucketName = "rjlmpic-1300589041";
        boolean useTrafficLimit = false;
        GetObjectRequest getObjectRequest = new GetObjectRequest(bucketName, key);
        File localFile = new File("my_test.json");
        ObjectMetadata objectMetadata = cosclient.getObject(getObjectRequest, localFile);
        System.out.println(objectMetadata.getContentLength());
    }

    /**
     * 下载文件
     */
    public static void download(HttpServletResponse response, String path) throws IOException {
        System.out.println(path);
        // 1 初始化用户身份信息(secretId, secretKey)
        COSCredentials cred = new BasicCOSCredentials("AKIDb0A1h6v5fy2oKicMaXMxHMJM8fwvs9OO","y6zbHgneZDbiX1EAqFO6YiiTx94j7D3j");
        // 2 设置 bucket 区域
        ClientConfig clientConfig = new ClientConfig(new Region("ap-nanjing"));
        // 3 生成 cos 客户端
        COSClient cosclient = new COSClient(cred, clientConfig);
        String bucketName = "rjlmpic-1300589041";

        System.out.println(bucketName+"---------"+path);
        GetObjectRequest getObjectRequest = new GetObjectRequest(bucketName, path);
        System.out.println(getObjectRequest.getKey());
        // 限流使用的单位是 bit/s, 这里设置下载带宽限制为10MB/s
        //getObjectRequest.setTrafficLimit(80*1024*1024);
        COSObject cosObject = cosclient.getObject(getObjectRequest);
        System.out.println(cosObject.toString());
        COSObjectInputStream cosObjectInput = cosObject.getObjectContent();

        // 下载对象的 CRC64
        //String crc64Ecma = cosObject.getObjectMetadata().getCrc64Ecma();
        response.reset();
        response.setContentType("application/x-msdownload;charset=utf-8");
        try {
            response.setHeader("Content-Disposition", "attachment;filename="+new String((path.split("/")[0]).getBytes("gbk"), "iso-8859-1"));//下载文件的名称
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        }
        ServletOutputStream sout = response.getOutputStream();
        BufferedInputStream bis = null;
        BufferedOutputStream bos = null;
        try {
            bis = new BufferedInputStream(cosObjectInput);
            bos = new BufferedOutputStream(sout);
            byte[] buff = new byte[2048];
            int bytesRead;
            while (-1 != (bytesRead = bis.read(buff, 0, buff.length))) {
                bos.write(buff, 0, bytesRead);
            }
            bos.flush();
            bos.close();
            bis.close();
        } catch (final IOException e) {
            throw e;
        } finally {
            if (bis != null){
                bis.close();
            }
            if (bos != null){
                bos.close();
            }
        }
        // 关闭输入流
        cosObjectInput.close();
    }

    /**
     * 生成临时密钥
     *
     * @return
     */
    private static JSONObject getTempKey() {
        TreeMap<String, Object> config = new TreeMap<String, Object>();
        try {//使用永久密钥生成临时密钥
            config.put("SecretId", secretId);
            config.put("SecretKey", secretKey);
            config.put("durationSeconds", Integer.parseInt(durationSeconds));
            config.put("bucket", bucket);
            config.put("region", region);
            config.put("allowPrefix", allowPrefix);
            //密钥的权限列表，其他权限列表请看
            //https://cloud.tencent.com/document/product/436/31923
            String[] allowActions = new String[]{
                    // 简单上传
                    "name/cos:PutObject",
                    // 表单上传、小程序上传
                    "name/cos:PostObject",
                    // 分片上传
                    "name/cos:InitiateMultipartUpload",
                    "name/cos:ListMultipartUploads",
                    "name/cos:ListParts",
                    "name/cos:UploadPart",
                    "name/cos:CompleteMultipartUpload",
                    "name/cos:GetObject"
            };
            config.put("allowActions", allowActions);
            JSONObject credential = CosStsClient.getCredential(config);
            //成功返回临时密钥信息，如下打印密钥信息
            System.out.println(credential);
            return credential;
        } catch (Exception e) {
            //失败抛出异常
            throw new IllegalArgumentException("no valid secret !");
        }
    }
}









/**  获取所有的文件key
 *
 *         // 1 初始化用户身份信息(secretId, secretKey)
 *         COSCredentials cred = new BasicCOSCredentials("AKIDb0A1h6v5fy2oKicMaXMxHMJM8fwvs9OO","y6zbHgneZDbiX1EAqFO6YiiTx94j7D3j");
 *         // 2 设置 bucket 区域
 *         ClientConfig clientConfig = new ClientConfig(new Region("ap-nanjing"));
 *         // 3 生成 cos 客户端
 *         COSClient cosclient = new COSClient(cred, clientConfig);
 *         String bucketName = "rjlmpic-1300589041";
 *         ListObjectsRequest listObjectsRequest = new ListObjectsRequest();
 *         // 设置bucket名称
 *         listObjectsRequest.setBucketName(bucketName);
 *         // prefix表示列出的object的key以prefix开始
 *         listObjectsRequest.setPrefix("");
 *         // 设置最大遍历出多少个对象, 一次listobject最大支持1000
 *         listObjectsRequest.setMaxKeys(1000);
 *         // listObjectsRequest.setDelimiter("/");
 *         ObjectListing objectListing = null;
 *         try {
 *             objectListing = cosclient.listObjects(listObjectsRequest);
 *         } catch (CosServiceException e) {
 *             e.printStackTrace();
 *         } catch (CosClientException e) {
 *             e.printStackTrace();
 *         }
 *         // common prefix表示表示被delimiter截断的路径, 如delimter设置为/, common prefix则表示所有子目录的路径
 *         List<String> commonPrefixs = objectListing.getCommonPrefixes();
 *         // object summary表示所有列出的object列表
 *         List<COSObjectSummary> cosObjectSummaries = objectListing.getObjectSummaries();
 *         for (COSObjectSummary cosObjectSummary : cosObjectSummaries) {
 *             // 文件的路径key
 *             String key = cosObjectSummary.getKey();
 *             // 文件的etag
 *             String etag = cosObjectSummary.getETag();
 *             // 文件的长度
 *             long fileSize = cosObjectSummary.getSize();
 *             // 文件的存储类型
 *             String storageClasses = cosObjectSummary.getStorageClass();
 *             System.out.println("key: " + key);
 *         }
 *         cosclient.shutdown();
 *
 *
 *
 *
 * **/
